package org.bigjava.novelplatform.common.utils;

import cn.hutool.core.util.HexUtil;
import org.bigjava.novelplatform.common.enums.PathMapEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.USER_HEAD_DISK_PATH;

/**
 * @author ykh
 */
public class UploadUtils {
    /**
     * 上传
     * @param multipartFile 上传文件
     * @param pathMap       上传类型
     * @return 上传后url地址
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static String upload(MultipartFile multipartFile, PathMapEnum pathMap) throws NoSuchAlgorithmException,
            IOException {
        StringBuilder disk = new StringBuilder(pathMap.getDiskPath());
        StringBuilder mapNetwork = new StringBuilder(pathMap.getNetworkPath());
        if (multipartFile != null) {
            String filename = multipartFile.getOriginalFilename();
            assert filename != null;
            final MessageDigest md5 = MessageDigest.getInstance("MD5");
            final byte[] digest = md5.digest(filename.getBytes(StandardCharsets.UTF_8));
            final String encodeHexStr = HexUtil.encodeHexStr(digest);
            filename = encodeHexStr.substring(0,8);
            disk.append(filename);
            mapNetwork.append(filename);
            File file = new File(StringUtils.toString(disk));
            multipartFile.transferTo(file);
        }else{
            mapNetwork = null;
        }
        return StringUtils.toString(mapNetwork);
    }
}
